<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
      <el-button
        type="primary"
        plain
        icon="el-icon-plus"
        size="mini"
        @click="handleView()"
        class="manage-add-btn"
        >添加人员</el-button
      >
      <el-button
        type="primary"
        plain
        icon="el-icon-setting"
        size="mini"
        @click="showWatches()"
        class="manage-add-btn"
        >设置手环</el-button
      >
    </el-form>
    <el-table
      ref="tables"
      v-loading="loading"
      :data="list"
      :default-sort="defaultSort"
      @sort-change="handleSortChange"
      @selection-change="handleSelectionChange"
      @select="handleSelect"
    >
      <el-table-column type="selection" width="55" :selectable="checkSelectable"></el-table-column>
      <el-table-column label="用户ID" align="center" prop="userNumber" />
      <el-table-column label="用户头像" align="center">
        <template slot-scope="{ row }">
          <el-avatar :size="66" :src="formattedHeadIcon(row.photo)"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="部门" align="center" prop="deptName" />
      <el-table-column label="岗位" align="center" prop="positionName" />
      <el-table-column label="账号状态" align="center">
        <template slot-scope="{ row }">
          <el-tag
            effect="dark"
            v-if="row.online == 0"
            size="mini"
            type="success"
            >在线</el-tag
          >
          <el-tag effect="dark" v-else size="mini" type="info">掉线</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="imei" align="center" prop="imei" />
      <el-table-column label="手环电话" align="center" prop="braceletPhone" />
      <el-table-column label="入职时间" align="center" prop="hireDate" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleView(scope.row, scope.index)"
            >修改</el-button
          >
          <!-- <el-button v-if="scope.row.status == 0" size="mini" type="text" @click="handleFrost(scope.row, scope.index)">冻结</el-button>
          <el-button v-else size="mini" type="text" @click="handleFrost(scope.row, scope.index)">解冻</el-button> -->
          <el-button
            size="mini"
            type="text"
            style="color: #f56c6c"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 操作日志详细 -->
    <el-dialog
      :title="form.title"
      :visible.sync="open"
      width="800px"
      append-to-body
    >
      <el-form
        ref="form"
        :model="form"
        label-width="100px"
        size="mini"
        :rules="rules"
      >
        <el-form-item label="姓名：" prop="name" style="width: 60%">
          <el-input
            v-model="form.name"
            type="text"
            placeholder="请输入姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户工号：" prop="userNumber" style="width: 68.2%">
          <el-input
            style="width: 85%"
            v-model="form.userNumber"
            type="text"
            placeholder="请输入用户ID"
          ></el-input>
          <el-button
            type="text"
            plain
            size="mini"
            @click="generateNumber()"
            class="manage-add-btn"
            >随机生成</el-button
          >
        </el-form-item>
        <el-form-item label="imei：" prop="imei" style="width: 60%">
          <el-input
            v-model="form.imei"
            type="text"
            placeholder="请输入imei"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号码：" style="width: 60%">
          <el-input
            v-model="form.phone"
            type="tel"
            placeholder="请输入手机号码"
            maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item label="手环电话" style="width: 60%">
          <el-input
            v-model="form.braceletPhone"
            type="tel"
            placeholder="请输入手机号码"
            maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户头像：" style="width: 60%">
          <ImageUpload
            :value="form.photo"
            :limit="1"
            :isShowTip="isShowTip"
            @dataSent="handleDataFromChild"
          />
        </el-form-item>
        <el-form-item label="部门：" prop="tap">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </el-form-item>
        <el-form-item label="岗位：" prop="member">
          <el-select
            placeholder="请选择岗位"
            v-model="form.position"
            clearable
            filterable
          >
            <el-option
              v-for="(m, index) in postList"
              :key="index"
              :label="m.postName"
              :value="m.postId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入职时间：">
          <el-date-picker v-model="hireDate" type="date" placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="submit()">提 交</el-button>
      </div>
    </el-dialog>
    <!-- 设置手环操作 -->
    <el-dialog
      title="手环信息"
      :visible.sync="openWatche"
      width="60%"
      append-to-body
    >
      <el-tabs tab-position="left">
        <el-tab-pane label="SOS号码">
          <el-form
            ref="form"
            :model="watcheForm.SOS"
            label-width="100px"
            size="mini"
          >
            <el-form-item label="联系人1：" prop="sos1" style="width: 60%">
              <el-input
                v-model="watcheForm.SOS.sos1"
                type="text"
                placeholder="请输入联系人"
              ></el-input>
            </el-form-item>
            <el-form-item label="联系人2：" prop="sos2" style="width: 60%">
              <el-input
                v-model="watcheForm.SOS.sos2"
                type="text"
                placeholder="请输入联系人"
              ></el-input>
            </el-form-item>
            <el-form-item label="联系人3：" prop="sos3" style="width: 60%">
              <el-input
                v-model="watcheForm.SOS.sos3"
                type="text"
                placeholder="请输入联系人"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitWatche('SOS')"
                >提交</el-button
              >
              <el-button @click="resetWatche('SOS')">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="测量间隔">
          <el-form
            ref="form"
            :model="watcheForm.GAP"
            label-width="120px"
            size="mini"
          >
            <el-form-item
              label="定位间隔(分钟)："
              prop="locationtimeinterval"
              style="width: 60%"
            >
              <el-input
                v-model="watcheForm.GAP.locationtimeinterval"
                type="text"
                placeholder="请输入定位间隔"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="心率间隔(分钟)："
              prop="heartratetimeinterval"
              style="width: 60%"
            >
              <el-input
                v-model="watcheForm.GAP.heartratetimeinterval"
                type="text"
                placeholder="请输入心率间隔"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="体温间隔(分钟)："
              prop="tpi"
              style="width: 60%"
            >
              <el-input
                v-model="watcheForm.GAP.tpi"
                type="text"
                placeholder="请输入体温间隔"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="血压间隔(分钟)："
              prop="bpi"
              style="width: 60%"
            >
              <el-input
                v-model="watcheForm.GAP.bpi"
                type="text"
                placeholder="请输入血压间隔"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="血氧间隔(分钟)："
              prop="oxi"
              style="width: 60%"
            >
              <el-input
                v-model="watcheForm.GAP.oxi"
                type="text"
                placeholder="请输入血氧间隔("
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitWatche('GAP')"
                >提交</el-button
              >
              <el-button @click="resetWatche('GAP')">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="健康阈值">
          <el-form
            ref="form"
            :model="watcheForm.BP"
            label-width="120px"
            size="mini"
          >
            <el-form-item
              label="最大心率："
              prop="maxheartrate"
              style="width: 60%"
            >
              <el-input
                v-model="watcheForm.BP.maxheartrate"
                type="text"
                placeholder="请输入最大心率"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="最小心率："
              prop="minheartrate"
              style="width: 60%"
            >
              <el-input
                v-model="watcheForm.BP.minheartrate"
                type="text"
                placeholder="请输入最小心率"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="高压最大："
              prop="bphighmax"
              style="width: 60%"
            >
              <el-input
                v-model="watcheForm.BP.bphighmax"
                type="text"
                placeholder="请输入高压最大"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="高压最小："
              prop="bphighmin"
              style="width: 60%"
            >
              <el-input
                v-model="watcheForm.BP.bphighmin"
                type="text"
                placeholder="请输入高压最小"
              ></el-input>
            </el-form-item>
            <el-form-item label="低压最大：" prop="bplowmax" style="width: 60%">
              <el-input
                v-model="watcheForm.BP.bplowmax"
                type="text"
                placeholder="请输入低压最大"
              ></el-input>
            </el-form-item>
            <el-form-item label="低压最小：" prop="bplowmin" style="width: 60%">
              <el-input
                v-model="watcheForm.BP.bplowmin"
                type="text"
                placeholder="请输入低压最小"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="血氧最大："
              prop="bloodoxmax"
              style="width: 60%"
            >
              <el-input
                v-model="watcheForm.BP.bloodoxmax"
                type="text"
                placeholder="请输入血氧最大"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="血氧最小："
              prop="bloodoxmin"
              style="width: 60%"
            >
              <el-input
                v-model="watcheForm.BP.bloodoxmin"
                type="text"
                placeholder="请输入血氧最小"
              ></el-input>
            </el-form-item>
            <el-form-item label="体温最大：" prop="tempmax" style="width: 60%">
              <el-input
                v-model="watcheForm.BP.tempmax"
                type="text"
                placeholder="请输入体温最大"
              ></el-input>
            </el-form-item>
            <el-form-item label="体温最小：" prop="tempmin" style="width: 60%">
              <el-input
                v-model="watcheForm.BP.tempmin"
                type="text"
                placeholder="请输入体温最小"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitWatche('BP')"
                >提交</el-button
              >
              <el-button @click="resetWatche('BP')">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
import {
  list,
  frost,
  addEmployee,
  delEmployee,
  editEmployee,
  setWatches,
} from "@/api/personnel/manage";
import { deptChildTreeSelect, deptTreeSelect } from "@/api/system/user";
import { listPost } from "@/api/system/post";
const prefix = process.env.VUE_APP_CDN_HOST;
import store from "@/store";

export default {
  name: "Operlog",
  data() {
    return {
      rules: {
        name: [{ required: true, message: "请填写姓名", trigger: "blur" }],
        userNumber: [
          { required: true, message: "请填写用户ID", trigger: "blur" },
        ],
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 默认排序
      defaultSort: { prop: "operTime", order: "descending" },
      // 表单参数
      form: {
          title: "添加人员",
          userNumber: "",
          name: "",
          imei: "",
          phone: "",
          braceletPhone: "",
          photo: "",
          position: null,
          deptId: null,
          deptName: "",
        },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        operIp: undefined,
        title: undefined,
        operName: undefined,
        businessType: undefined,
        status: undefined,
      },
      // 岗位列表
      postList: [],
      // 部门树选项
      deptOptions: undefined,
      defaultProps: {
        children: "children",
        label: "deptName",
      },
      isShowTip: true,
      hireDate: "",
      isAdd: true,
      //手环
      openWatche: false,
      watcheForm: {
        imeis: [],
        SOS: {},
        GAP: {},
        BP: {},
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleDataFromChild(data) {
      this.form.photo = data[0].url;
      this.isShowTip = false;
    },
    /** 查询登录日志 */
    getList() {
      this.loading = true;
      list(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.list = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.pageNum = 1;
      this.$refs.tables.sort(this.defaultSort.prop, this.defaultSort.order);
    },
    /** 排序触发事件 */
    handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.isAsc = column.order;
      this.getList();
    },
    /** 详细按钮操作 */
    handleView(row) {
      this.getDeptTree();
      listPost().then((response) => {
        this.postList = response.rows;
      });
      this.open = true;
      if (row) {
        // 编辑：将行数据浅拷贝到表单，设置入职时间并根据 photo 控制提示显示
        this.isAdd = false;
        this.form.title = "修改人员";
        this.form = Object.assign({}, row);
        this.hireDate = row.hireDate
          ? new Date(row.hireDate + "T00:00:00Z").toISOString()
          : "";
        this.isShowTip = !!this.form.photo;
        // 如果树存在，尝试把当前节点定位到部门
        this.$nextTick(() => {
          if (this.$refs.tree && this.form.deptId) {
            try {
              this.$refs.tree.setCurrentKey(this.form.deptId);
            } catch (e) {
              console.log(e);
            }
          }
        });
      } else {
        this.isAdd = true;
        this.form = {
          title: "添加人员",
          userNumber: "",
          name: "",
          imei: "",
          phone: "",
          braceletPhone: "",
          photo: "",
          position: null,
          deptId: null,
          deptName: "",
        };
        this.hireDate = "";
        this.isShowTip = true;
        this.$nextTick(() => {
          if (this.$refs.tree) {
            try {
              this.$refs.tree.setCurrentKey(null);
            } catch (e) {
              console.log(e);
            }
          }
        });
      }
    },
    //删除员工
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除名称为"' + row.name + '"的员工？')
        .then(function () {
          return delEmployee(row.id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    //冻结状态
    handleFrost(row) {
      frost({ id: row.id }).then((response) => {
        if (response.code === 200) {
          this.$modal.msgSuccess(response.msg);
          this.getList();
        }
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      const deptId = store.getters.deptId;
      deptChildTreeSelect(deptId).then((response) => {
        this.deptOptions = response.data;
      });
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.form.deptId = data.deptId;
      this.form.deptName = data.deptName;
    },
    //随机生成用户ID
    generateNumber() {
      const random8DigitNumber =
        Math.floor(Math.random() * (99999999 - 10000000 + 1)) + 10000000;
      this.form.userNumber = random8DigitNumber;
    },
    submit() {
      if (this.isAdd) {
        this.form.hireDate = this.moment(this.hireDate).format("YYYY-MM-DD");
        addEmployee(this.form).then((response) => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      } else {
        this.form.hireDate = this.moment(this.hireDate).format("YYYY-MM-DD");
        editEmployee(this.form).then((response) => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      }
    },
    //设置手环
    showWatches() {
      if (this.watcheForm.imeis.length == 0) {
        this.$modal.msgError("请选择存在imei的人员");
        return;
      }
      this.openWatche = true;
    },
    handleSelectionChange(val) {
      console.log(val);
      if (val.length == 1) {
        this.watcheForm.SOS = {
          sos1: val[0].sos1,
          sos2: val[0].sos2,
          sos3: val[0].sos3,
        };
        this.watcheForm.GAP = {
          locationtimeinterval: val[0].locationTimeInterval,
          heartratetimeinterval: val[0].heartRateTimeInterval,
          tpi: val[0].tpi,
          bpi: val[0].bpi,
          oxi: val[0].oxi,
        };

        this.watcheForm.BP = {
          maxheartrate: val[0].maxHeartRate,
          minheartrate: val[0].minHeartRate,
          bphighmax: val[0].bpHighMax,
          bphighmin: val[0].bpHighMin,
          bplowmax: val[0].bpLowMax,
          bplowmin: val[0].bpLowMin,
          bloodoxmax: val[0].bloodOxMax,
          bloodoxmin: val[0].bloodOxMin,
          tempmax: val[0].tempMax,
          tempmin: val[0].tempMin,
        };
      }
      this.watcheForm.imeis = [];
      val.forEach((item) => {
        if (item.imei) {
          this.watcheForm.imeis.push(item.imei);
        }
      });
      console.log(this.watcheForm);
    },
    formattedHeadIcon(icon) {
      return prefix + icon;
    },
    // 控制是否可选
    checkSelectable(row, index) {
      return this.$refs.tables.selection.length === 0 || this.$refs.tables.selection.includes(row);
    },
    // 选择事件处理
    handleSelect(selection, row) {
      // 如果选中数量超过1，则只保留最后选中的
      if (selection.length > 1) {
        // 清空之前的选择
        this.$refs.tables.clearSelection();
        // 选中当前行
        this.$refs.tables.toggleRowSelection(row, true);
      }
    },
    submitWatche(type) {
      const sosdata = {
        imeis: this.watcheForm.imeis,
        ...this.watcheForm.SOS,
        ...this.watcheForm.GAP,
        ...this.watcheForm.BP,
      };
      setWatches(sosdata).then(() => {
        this.$modal.msgSuccess("设置成功");
        this.openWatche = false;
        this.getList();
      });

      // switch (type) {
      //   case 'SOS':
      //     const sosdata = {
      //       imeis: this.watcheForm.imeis,
      //       ...this.watcheForm.SOS,
      //     };
      //     setWatches(sosdata).then(() => {
      //       this.$modal.msgSuccess("设置成功");
      //       this.openWatche = false;
      //       this.getList();
      //     });
      //     break;
      //   case 'GAP':
      //     const gapdata = {
      //       imeis: this.watcheForm.imeis,
      //       ...this.watcheForm.GAP,
      //     };
      //     setWatches(gapdata).then(() => {
      //       this.$modal.msgSuccess("设置成功");
      //       this.openWatche = false;
      //       this.getList();
      //     });
      //     break;
      //   case 'BP':
      //     const bpdata = {
      //       imeis: this.watcheForm.imeis,
      //       ...this.watcheForm.BP,
      //     };
      //     setWatches(bpdata).then(() => {
      //       this.$modal.msgSuccess("设置成功");
      //       this.openWatche = false;
      //       this.getList();
      //     });
      //     break;
      //   default:
      //     break;
      // }
    },
    resetWatche(type) {
      switch (type) {
        case "SOS":
          this.watcheForm.SOS = {};
          break;
        case "GAP":
          this.watcheForm.GAP = {};
          break;
        case "BP":
          this.watcheForm.BP = {};
          break;
        default:
          break;
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.manage-add-btn {
  float: right;
  margin-left: 10px;
}
</style>
